#include <iostream>
#include <queue>
#include <vector>
#include <string>
#include <unistd.h>
#include "Task.hpp"

using namespace std;

const int defaultnum = 5;

struct ThreadInfo
{
    pthread_t tid;
    string name;
};

template <class T>
class ThreadPool
{
public:
    string GetThreadname(pthread_t tid)
    {
        for(auto &v:_vthread)
        {
            if(v.tid==tid)
            {
                return v.name;
            }
        }
    }

    static void* RunThread(void* args)
    {
        ThreadPool<T>* th = static_cast<ThreadPool<T>*>(args);

        string name = th->GetThreadname(pthread_self());

        while(1)
        {
            pthread_mutex_lock(&(th->_mutex));

            while(th->_q.empty())
            {
                pthread_cond_wait(&(th->_cond),&(th->_mutex));
            }
            Task data = th->pop();

            pthread_mutex_unlock(&(th->_mutex));

            data.run();
            cout << name << " 处理了一个任务" << data.GetResult() << endl;
        }
    }


public:
    ThreadPool(int size = defaultnum)
        : _vthread(size)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }

    void start()
    {
        for(int i=0;i<_vthread.size();i++)
        {
            _vthread[i].name = "thread" + to_string(i+1);
            pthread_create(&(_vthread[i].tid),nullptr,RunThread,this);
        }
    }

    void push(const T& data)
    {
        pthread_mutex_lock(&_mutex);
        _q.push(data);

        pthread_cond_signal(&_cond);

        pthread_mutex_unlock(&_mutex);
    }

    T pop()
    {
        T data = _q.front();
        _q.pop();

        return data;
    }

    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

private:
    vector<ThreadInfo> _vthread;
    queue<T> _q;

    pthread_mutex_t _mutex;
    pthread_cond_t _cond;
};